package cn.cxyxj.code_auth_jwt_persistence_prod.config;

import cn.cxyxj.code_auth_jwt_persistence_prod.entity.SysUserDetails;
import cn.cxyxj.code_auth_jwt_persistence_prod.utils.RedisUtil;
import cn.hutool.core.util.StrUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2RefreshToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2Request;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.stereotype.Component;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

/**
 * 自定义 jwt token 信息
 */
// extends JwtAccessTokenConverter {
// implements TokenEnhancer {
public class CustomAdditionalInformation extends JwtAccessTokenConverter {

    private static final String ACCESS = "access:%s";
    private static final String REFRESH = "refresh:%s";

    /**
     *
     * @param accessToken:Token 信息对象，可以往里面添加额外信息
     * @param authentication：OAuth2认证信息对象
     * @return
     */
    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {

        Map<String, Object> additionalInformation = new LinkedHashMap<>();

        // 包含 /oauth/token接口的 OAuth2 请求信息
        OAuth2Request oAuth2Request = authentication.getOAuth2Request();
        String clientId = oAuth2Request.getClientId();
        if(StrUtil.isEmpty(clientId)){
            // 直接登录认证中心
        }else {
            // 第三方登录
        }
        // 判断当前客户端是否内部应用，如果是，则在 Token 添加用户菜单、用户权限信息
        // 如果如需要当前登录用户信息，也可以从 SecurityContextHolder 中获取。
        Object principal = authentication.getUserAuthentication().getPrincipal();
        if(principal instanceof SysUserDetails){
            Set<String> urlSet = ((SysUserDetails) principal).getUrlSet();
            additionalInformation.put("urlSet", urlSet);
        }
        Authentication authentication1 = SecurityContextHolder.getContext().getAuthentication();
        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInformation);

        OAuth2AccessToken enhance = super.enhance(accessToken, authentication);
        String value = enhance.getValue();
        String refreshToken = enhance.getRefreshToken().getValue();
        RedisUtil.set(String.format(ACCESS,value),accessToken);
        RedisUtil.set(String.format(REFRESH,refreshToken),accessToken);
        return enhance;
    }

}